//
//  JMAuthVC.m
//  NewiOSProject
//
//  Created by apple on 2023/11/29.
//  Copyright © 2023 范智渊. All rights reserved.
//
#import "JMAuthVC.h"
#import "JMAuthCellModel.h"
#import "JMCustomCell.h"
#import "JMAuthStepView.h"
#import "JMSlicenseVC.h"
#import "JMProductVC.h"
@interface JMAuthVC (){
    BOOL hasShowWindow;//是否提示过挽留弹窗
    CGFloat top;
}
@property (nonatomic,assign)NSInteger step;
@property (nonatomic,strong)UIScrollView*mainSV;
@property (nonatomic,strong)JMAuthStepView*stepView;
@property (nonatomic,strong)NSMutableArray*allQues;//页面数据，每一步对应的model数组
@property (nonatomic, strong)JMLoadingButton *confirmBtn;
@property(nonatomic, strong, nonnull) NSArray *steps;
@property(nonatomic, strong, nonnull) JMQuestionModel *questionModel;
@end

@implementation JMAuthVC
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [JMCommonMethod userBehaviorTrack:self.questionModel.pageName FeatureName:@"Page" Action:OUT];
}
-(NSMutableArray *)allQues{
    if (!_allQues) {
        _allQues = [JMAuthCellModel defalutModelArray];
    }return _allQues;
}
-(void)backBtnClick{
    int rand = random() % 3;
    NSArray * words = @[
        @"Usted está a un paso para obtener el préstamo",
        @"Sólo 3 minutos para completar la autenticación",
        @"Está seguro de que no necesita el préstamo?"];
    @weakify(self);
    if(hasShowWindow){
        [super backBtnClick];
    }else{
        @weakify(self);
        [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 166)) Title:words[rand] subTitle:@"" BottomBtns:@[@"Confirmar"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor) btnActionBlock:^(NSInteger btnTag) {
            @strongify(self);
            if (hasShowWindow) {
                [super backBtnClick];
            }else{
                hasShowWindow = YES;
            }
        }];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavi];
    [self.view addSubview:self.mainSV];
    self.automaticallyAdjustsScrollViewInsets = false;
    self.mainSV.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.backBtn removeAllTargets];
    [self.backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self requestSteps];
    self.fd_interactivePopDisabled = YES;
}
-(void)setNavi{
    self.TitleLabel.textColor = WhiteColor();
    [self.backBtn setImage:ImageNamed(@"auth_back") forState:(UIControlStateNormal)];
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), NAVIGATION_BAR_HEIGHT()+154))];
    [self.NavImg addSubview:imgV];
    [imgV setImage:ImageNamed(@"auth_top")];
    [self.NavImg sendSubviewToBack:imgV];
    self.NavImg.clipsToBounds = YES;
    
}
/// 获取所有步骤
- (void)requestSteps {
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/auth/getAwardAmount") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSArray *list = (NSArray *)dataDic;
        if (list != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.steps = @[
                    @{@"CREDIT_INFO":dataDic[@"CREDIT_INFO"]},
                    @{@"IDENTITY_INFO":dataDic[@"IDENTITY_INFO"]},
                    @{@"LIVENESS_INFO":dataDic[@"LIVENESS_INFO"]},
                    @{@"PERSONAL_INFO":dataDic[@"PERSONAL_INFO"]},
                    @{@"INCOME_INFO":dataDic[@"INCOME_INFO"]},
                    @{@"CONTACT_INFO":dataDic[@"CONTACT_INFO"]},
                    @{@"BANK_INFO":dataDic[@"BANK_INFO"]},
                ];
                [self requestCurrentStep];
            });
        }
    } fail:nil];
}

/// 获取当前用户认证到哪一步了
- (void)requestCurrentStep {
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/loan/get-next-step2") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSString *step = (NSString *)dataDic[@"step"];
        
        if (step != nil) {
            if ([step isEqualToString:@"100"]) {
                //认证成功弹窗
                [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 227)) Title:@"Felicitaciones, ha completado todo el proceso de verificación" subTitle:@"Se busca un producto más adecuado para usted, la tasa de aprobación es de hasta el 90%,, solicite ahora" BottomBtns:@[@"OK"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor)btnActionBlock:^(NSInteger btnTag) {
                    [self.navigationController popViewControllerAnimated:YES];
                    //产品打包页
                    delayOperation(0.3, ^{
                        JMProductVC *vc = JMProductVC.new;
                        [UIWindow.jm_currentViewController.navigationController pushViewController:vc animated:YES];
                    });
                  
                }];
            }else{
                for (NSInteger i = 0; i < self.steps.count; i ++) {
                    NSDictionary *item = self.steps[i];
                    NSString *label = item.allKeys.firstObject;
                    if (label != nil) {
                        if ([label isEqualToString:step]) {
                            self.step = i + 1;
                            break;
                        }
                    }
                }
            }
        }
    } fail:nil];
}
///保存用户信息
-(void)saveInfo{
    
    NSDictionary *param = [self.questionModel toParam:self.step];
    [JMCommonMethod uploadStatistics:self.questionModel.pageName actionType:@"Save_Start" parameters:nil];

    if (_step==7) {
        if (![self.questionModel.bankCard1 isEqualToString:self.questionModel.bankCard]) {
            [JMProgressHelper toastInWindowWithMessage:@"*Nomor rekening yang dimasukkan salah"];
            return;
        }
    }
    [JMBaseRequest.sharedInstance requestBasePost:BasePostRequestUrl(@"/api/auth/save-user-info2") params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [JMCommonMethod uploadStatistics:self.questionModel.pageName actionType:@"Save_End" parameters:nil];

        [self requestSteps];
    } fail:nil];
}
-(void)setStep:(NSInteger)step{
    if (step<=0 || step>7) {
        return;
    }
    @weakify(self);
    _step = step;
    _confirmBtn.enable = NO;
    [_stepView removeFromSuperview];
    [_mainSV removeAllSubviews];
    [JMCommonMethod userBehaviorTrack:self.questionModel.pageName FeatureName:@"Page" Action:ENTER];

    _stepView = [[JMAuthStepView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), NAVIGATION_BAR_HEIGHT()+154)) steps:self.steps step:step];
    [self.mainSV addSubview:_stepView];
    
    NSArray *ques =self.allQues[step-1];
    top = self.stepView.bottom;
    
    for (int i=0; i<ques.count; i++) {
        JMAuthCellModel * model = ques[i];
        JMCustomCell *cell = [[JMCustomCell alloc]initWithModel:model];
        cell.tag = i+10;
        self.TitleLabel.text = model.vcTitle;
        cell.top = top;
        cell.inputCallback = ^(JMPickerSelectionModel * _Nonnull value) {
            @strongify(self);
            [self checkWithAuthModel:cell.model andValue:value];
            [cell updateErrorinfo];
            [self updateUI];
        };
        cell.ktpSuccess = ^(NSDictionary * _Nonnull data) {
            @strongify(self);
            delayOperation(0, ^{
                self.questionModel.livingSuccess = NO;

                JMCustomCell *nameCell = [self.mainSV viewWithTag:111];
                NSDictionary *idCardData = data[@"tongDunOCRResponseEntity"][@"idCardData"];
                nameCell.textF.text = idCardData[@"fullName"];
                JMCustomCell *idCell = [self.mainSV viewWithTag:222];
                idCell.textF.text = idCardData[@"idNumber"];
                
                delayOperation(0.01, ^{
                    [self checkWithAuthModel:cell.model andValue:data];
                });
            });
            
        };
        cell.livenessSuccess = ^(NSDictionary * _Nonnull data) {
            [self checkWithAuthModel:cell.model andValue:data];
        };
        [self.mainSV addSubview:cell];
        top = cell.bottom;
    }
    [self update];
}
-(void)update{
    [self.mainSV addSubview:self.confirmBtn];
    self.confirmBtn.top = top+30;
    [self.mainSV addSubview:self.footerView];
    self.footerView.top = self.confirmBtn.bottom+24;
    self.mainSV.contentSize =CGSizeMake(kAppW(), self.footerView.bottom+60);
    delayOperation(0.01, ^{
        [self.view sendSubviewToBack:self.mainSV];
    });
}
-(void)updateUI{
    JMCustomCell *cell1  = [self.mainSV viewWithTag:11];//卡号
    JMCustomCell *cell2  = [self.mainSV viewWithTag:12];//确认
    cell1.frame = cell1.frame;
    cell2.top = cell1.bottom;
    
    top = cell2.bottom;
    [self update];
}
-(void)checkWithAuthModel:(JMAuthCellModel *)authModel andValue:(JMPickerSelectionModel *)value{
    self.confirmBtn.enable = [self.questionModel checkWithAuthCellModel:authModel andValue:value];
}
-(JMLoadingButton *)confirmBtn{
    if (!_confirmBtn) {
        _confirmBtn = [[JMLoadingButton alloc]initWithFrame:(CGRectMake(24,0,kAppW()-48, 56)) title:@"Entregar" font:Font(17) titleLabelColor:HexAlpha_Str_COLOR(@"#ffffff", 1) backgoundColor:nil action:@selector(saveInfo) target:self];
        _confirmBtn.cornerRadius = 28;
        _confirmBtn.enable = NO;
    }return _confirmBtn;
}
-(UIScrollView *)mainSV{
    if (!_mainSV) {
        _mainSV = [[UIScrollView alloc]initWithFrame:(CGRectMake(0,0, kAppW(), kAppH()))];
        _mainSV.automaticallyAdjustsScrollIndicatorInsets = NO;
    }return _mainSV;
}
-(JMQuestionModel *)questionModel{
    if (!_questionModel) {
        _questionModel = [JMQuestionModel new];
    }return _questionModel;
}
@end
